#pragma once
#include<iostream>
#include<vector>
#include<string>
#include"InetAddr.hpp"

class Route
{
private:
    bool InExit(InetAddr addr)
    {
        for(auto&user:_online_user)
        {
            if(user==addr)
            {
                return true;
            }
        }
        return false;
    }
    void AddUser(InetAddr&addr)
    {
        if(InExit(addr)==false)
        {
            _online_user.push_back(addr);
        }
    }
    void SenMessage(int sockfd,std::string&message,InetAddr&addr)
    {
        for(auto&user:_online_user)
        {
            sendto(sockfd,message.c_str(),message.size(),0,addr.Addr(),addr.Len());
        }
    }
    void DeleteUser(const std::string &message,InetAddr&addr)
    {
        if(message == "QUIT")
        {
            auto iter = _online_user.begin();
            for(; iter != _online_user.end(); iter++)
            {
                if(*iter == addr)
                {
                    _online_user.erase(iter);
                    break;
                }
            }
        }
    }
public:
    Route(){}
    void SendMessageToAll(int sockfd,std::string&message,InetAddr&addr)
    {
        //1.添加用户
        AddUser(addr);
        //2.转发消息
        SenMessage(sockfd,message,addr);
        //3.删除用户
        DeleteUser(message,addr);
    }
    ~Route(){}
private:
    std::vector<InetAddr> _online_user;
};